import {Injectable} from '@angular/core';
import {LoadingController, ToastController} from "ionic-angular";
import * as _ from 'lodash';
import {loadingUrls} from "../../config/url-needLoading.config";

@Injectable()
export class LoadingService {

    loading: any;

    constructor(public loadCtr: LoadingController, public toastCtrl: ToastController) {
    }

    /**
     * 判断是否需要loading
     * @param {string | Request} url
     * @returns {boolean}
     */
    static isNeedLoading(url: string): boolean {
        return _.indexOf(loadingUrls, url) !== -1;
    }

    showLoading(url: string) {
        if (!this.loading && LoadingService.isNeedLoading(url)) {
            this.loading = this.loadCtr.create({
                content: "请稍候...",
            });
            this.loading.present();
        }
    }

    dismissLoading() {
        if (this.loading) {
            this.loading.dismiss();
            this.loading = null;
        }
    }

    errToast(message: string) {
        this.toastCtrl.create({
            message: message,
            duration: 1200,
            position: 'bottom'
        }).present();
    }
}
